﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Profile;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;
using Facade;
using System.Collections;
using System.Data;

namespace IronOne.SalesOne.SalesOneWeb.CustomerServices
{
    public partial class AcknowledgeSlip : SOSecurityPage, IDataPage,IntTest
    {
        private int pageNo = 1;
        StructureFacade facade;
        int userType;
        public static List<Branch> brnch;
        public static List<SalesOneUnit> un;
        public static List<string> so;


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ValidateUserCredentials(Request.Url.LocalPath);
                //lblError.Text = "";
                facade = new StructureFacade();
                string csType = string.Empty;
                if (!IsPostBack)
                {


                    if (Request.QueryString["cs"] != null)
                    {
                        csType = Request.QueryString["cs"].ToString();
                    }


                    switch (csType)
                    {
                        case "ack":
                            btnView.Visible = false;
                            ListItem itemSel = new ListItem("Select...");
                            drpStatus.Items.Insert(0, itemSel);
                            ListItem itemSig = new ListItem("Signed");
                            drpStatus.Items.Insert(1, itemSig);
                            ListItem itemUnsig = new ListItem("Unsigned");
                            drpStatus.Items.Insert(2, itemUnsig);
                            break;

                        case "pep":

                            ListItem itemSel1 = new ListItem("Select...");
                            drpStatus.Items.Insert(0, itemSel1);
                            ListItem itemPen = new ListItem("Pending");
                            drpStatus.Items.Insert(1, itemPen);
                            ListItem itemCl = new ListItem("Clear");
                            drpStatus.Items.Insert(2, itemCl);

                            //CodeFacade cFac = new CodeFacade();
                            //List<PendingStatus> penStat = cFac.GetPendingStatuss("CodeId ASC");

                            //PendingStatus penSel = new PendingStatus();
                            //penSel.CodeId = -1;
                            //penSel.Code = "Select";
                            //penStat.Insert(0, penSel);

                            //drpStatus.DataSource = penStat;
                            //drpStatus.DataTextField = "Code";
                            //drpStatus.DataValueField = "CodeId";
                            //drpStatus.DataBind();
                            break;
                        default:
                            break;
                    }

                    User user = facade.GetUser(User.Identity.Name);
                    UserInformation info = facade.GetUserInformation(User.Identity.Name);
                    userType = info.UserType;


                    bool flag = false;

                    if (userType == 4)
                    {
                        if (user.SoCode != null)
                        {
                            //drpSoCodes.Items.Add(user.SoCode);
                            //drpSoCodes.SelectedIndex = drpSoCodes.Items.Count - 1;

                            //drpSoCodes.Enabled = false;
                            populateSOCodes(facade.GetSOsInUnit(user.NodeId));
                        }
                        else
                            populateSOCodes(facade.GetSOsInUnit(user.NodeId));
                        flag = true;
                    }

                    if (flag == true)
                    {
                        ListItem ls = new ListItem();
                        ls.Text = info.UnitName;
                        ls.Value = info.UnitId.ToString();

                        drpUnitCode.Items.Add(ls);
                        drpUnitCode.SelectedIndex = drpUnitCode.Items.Count - 1;

                        drpUnitCode.Enabled = false;
                    }
                    else if (userType == 3)
                    {
                        populateUnits(facade.GetUnitsForBranch(user.NodeId));
                        addDefaultItem(drpSoCodes);
                        flag = true;
                    }

                    if (flag == true)
                    {
                        ListItem ls = new ListItem();
                        ls.Text = info.BranchName;
                        ls.Value = info.BranchId.ToString();
                        drpBranch.Items.Add(ls);
                        drpBranch.SelectedIndex = drpBranch.Items.Count - 1;

                        drpBranch.Enabled = false;
                    }
                    else if (userType == 2)
                    {
                        populateBranches(facade.GetBranchesForGroup(user.NodeId));
                        addDefaultItem(drpUnitCode);
                        addDefaultItem(drpSoCodes);
                        flag = true;
                    }

                    if (userType == 1)
                        populateBranches(facade.GetBranches("BranchName ASC"));
                    addDefaultItem(drpUnitCode);
                    addDefaultItem(drpSoCodes);


                }
            }
            catch (Exception)
            {
                
            }
            
        }


        private void populateBranches(List<Branch> branches)
        {
            try
            {
                drpBranch.DataSource = branches;
                drpBranch.DataTextField = "BranchName";
                drpBranch.DataValueField = "BranchID";
                drpBranch.DataBind();

                addDefaultItem(drpBranch);
            }
            catch (Exception)
            {
                
            }
            
        }


        private void populateUnits(List<SalesOneUnit> units)
        {
            try
            {
                drpUnitCode.DataSource = units;
                drpUnitCode.DataTextField = "Name";
                drpUnitCode.DataValueField = "UnitID";
                drpUnitCode.DataBind();

                addDefaultItem(drpUnitCode);
            }
            catch (Exception)
            {

            }
            
        }

        private void populateSOCodes(List<string> users)
        {
            try
            {
                drpSoCodes.Items.Clear();
                foreach (string str in users)
                {
                    drpSoCodes.Items.Add(str);
                }
                addDefaultItem(drpSoCodes);
            }
            catch (Exception)
            {
            }
            
        }

        private void addDefaultItem(DropDownList ddl)
        {
            ListItem newItem = new ListItem("Select...");
            ddl.Items.Insert(0, newItem);
        }

        protected void drpBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (drpBranch.SelectedIndex > 0)
                {
                    populateUnits(facade.GetUnitsInBranch(int.Parse(drpBranch.SelectedValue)));
                    drpUnitCode.SelectedIndex = 0;

                    so = new List<string>();
                    populateSOCodes(so);
                }
                else
                {
                    List<SalesOneUnit> units = new List<SalesOneUnit>();
                    populateUnits(units);

                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception)
            {

            }
            
        }

        protected void drpUnitCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (drpUnitCode.SelectedIndex > 0)
                {
                    populateSOCodes(facade.GetSOsInUnit(int.Parse(drpUnitCode.SelectedValue)));
                }
                else
                {
                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception)
            {
                
            }
            

        }

        protected void drpSoCodes_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void searchButton_Click(object sender, EventArgs e)
        {
            pageNo = 1;

            string csType = string.Empty;
            if (Request.QueryString["cs"] != null)
            {
                csType = Request.QueryString["cs"].ToString();
            }
            

            switch (csType)
            {
                case "ack":
                    SearchAck(csType,1);
                    break;
                case "pep":
                    SearchAck(csType,1);
                    break;
                default:
                    break;
            }

        }



        private void SearchAck(string type, int pageNo)
        {
            try
            {
                CustomerFacade cusFac = new CustomerFacade();

                string contractId = txtContractId.Text;
                string status = string.Empty;
                int branchId;
                int unitId;
                string soCode = string.Empty;


                if (drpStatus.SelectedValue != "Select...")
                {
                    status = drpStatus.SelectedValue;
                }

                if (drpBranch.SelectedValue != "Select...")
                {
                    branchId = int.Parse(drpBranch.SelectedValue);
                    Branch brs = facade.GetBranch(branchId);
                    brnch = new List<Branch>();
                    brnch.Add(brs);
                }
                else
                {
                    int co2 = brnch.Count;
                    brnch.RemoveRange(0, co2);
                }


                if (drpUnitCode.SelectedValue != "Select..." && drpUnitCode.SelectedIndex != -1)
                {
                    unitId = int.Parse(drpUnitCode.SelectedValue);
                    SalesOneUnit sun = facade.GetUnit(unitId);
                    un = new List<SalesOneUnit>();
                    un.Add(sun);
                }
                else
                {
                    int co1 = un.Count;
                    un.RemoveRange(0, co1);
                }

                if (drpSoCodes.SelectedValue != "Select..." && drpSoCodes.Items.Count > 0)
                {
                    soCode = drpSoCodes.SelectedValue;
                    so = new List<string>();
                    so.Add(soCode);
                }
                else
                {
                    int co = so.Count;
                    so.RemoveRange(0, co);
                }



                SearchCS ackSearch = new SearchCS();
                ackSearch.ContractId = contractId;
                ackSearch.Status = status;
                ackSearch.Brnch = brnch;
                ackSearch.Unt = un;
                ackSearch.SOCode = so;

                if (brnch != null && un != null)
                {
                    if (pageNo == 1)
                    {
                        UCGrid1.SetText("1");
                    }

                    if (type == "ack")
                    {
                        List<Policy> ackPol = cusFac.SearchAckSlips(ackSearch, pageNo);
                        if (ackPol.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                        {
                            UCGrid1.IsLastPage = (cusFac.SearchAckSlips(ackSearch, pageNo + 1)).Count > 0 ? false : true;
                        }

                        if (ackPol != null)
                        {
                            if (pageNo == 1)
                            {
                                UCGrid1.SetText("1");
                            }

                            string contId = string.Empty;
                            string issueDate = string.Empty;
                            string soc = string.Empty;
                            string ackType = string.Empty;

                            DataTable usrTable = new DataTable();
                            DataRow newRow;
                            HyperLink hl;

                            usrTable.Columns.Add("Sign Flag");
                            usrTable.Columns.Add("Contract No");
                            usrTable.Columns.Add("Issued Date");
                            usrTable.Columns.Add("SC Code");

                            foreach (Policy pol in ackPol)
                            {
                                if (pol != null)
                                {
                                    contId = pol.ContractId;
                                    issueDate = pol.LastUpdatedDate;
                                    soc = pol.SOCode;
                                    ackType = pol.AckStatus;
                                    //hl = new HyperLink();
                                    //hl.NavigateUrl = "~/ContactManagement/PolicyDetails.aspx?con=" + contId;
                                    //string url = "~/ContactManagement/PolicyDetails.aspx?con=" + contId;

                                    newRow = usrTable.NewRow();

                                    newRow[0] = ackType;
                                    newRow[1] = contId;
                                    newRow[2] = issueDate;
                                    newRow[3] = soc;

                                    usrTable.Rows.Add(newRow);


                                }
                            }



                            int[] dispArr = { 0, 1 };
                            UCGrid1.SetDataSource(usrTable, dispArr);

                            if (usrTable.Rows.Count > 0)
                            {

                            }
                            else
                            {
                                MassageSummery("IIS504");
                                //lblError.Text = "No data to display.";
                            }

                            GridView gv = (GridView)UCGrid1.FindControl("grdUsers");
                            if (gv != null)
                            {
                                foreach (GridViewRow row in gv.Rows)
                                {
                                    hl = new HyperLink();
                                    string con = row.Cells[3].Text;
                                    hl.NavigateUrl = "~/ContactManagement/PolicyDetails.aspx?con=" + con + "&p=a";
                                    hl.Text = con;

                                    row.Cells[3].Controls.Add(hl);
                                }
                            }
                        }
                        else
                        {
                            DataTable dt = new DataTable();
                            int[] dispArr = { 0, 1 };
                            UCGrid1.SetDataSource(dt, dispArr);
                            MassageSummery("IIS504");

                        }



                    }
                    else if (type == "pep")
                    {
                        List<PendingProposal> penProp = cusFac.SearchPendProps(ackSearch, pageNo);
                        if (penProp.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                        {
                            UCGrid1.IsLastPage = (cusFac.SearchPendProps(ackSearch, pageNo + 1)).Count > 0 ? false : true;
                        }

                        if (penProp != null)
                        {
                            string contId = string.Empty;
                            int lifeNo;
                            string pendingReq = string.Empty;
                            string scCode = string.Empty;


                            DataTable usrTable = new DataTable();
                            DataRow newRow;

                            usrTable.Columns.Add("Clear Flag");
                            usrTable.Columns.Add("Contract No");
                            usrTable.Columns.Add("Life No");
                            usrTable.Columns.Add("Pending Requirement");
                            usrTable.Columns.Add("SO Code");

                            //hidden cols
                            usrTable.Columns.Add("Prop Date");
                            usrTable.Columns.Add("Comments");
                            usrTable.Columns.Add("Life Name");
                            usrTable.Columns.Add("Status");
                            usrTable.Columns.Add("Last Updated");

                            foreach (PendingProposal prop in penProp)
                            {
                                if (prop != null)
                                {
                                    contId = prop.ContractId;
                                    lifeNo = prop.LifeNo;
                                    pendingReq = prop.PendingRequirement;
                                    scCode = prop.SOCode;


                                    newRow = usrTable.NewRow();

                                    newRow[0] = prop.Status;
                                    newRow[1] = contId;
                                    newRow[2] = lifeNo;
                                    newRow[3] = pendingReq;
                                    newRow[4] = scCode;

                                    newRow[5] = prop.ProposalDate;
                                    newRow[6] = prop.Comments;
                                    newRow[7] = prop.LifeName;
                                    newRow[8] = prop.Status;
                                    newRow[9] = prop.LastUpdated;


                                    usrTable.Rows.Add(newRow);


                                }
                            }

                            int[] dispArr = { 1, 7, 8, 9, 10, 11 };
                            UCGrid1.SetDataSource(usrTable, dispArr);

                            if (usrTable.Rows.Count > 0)
                            {
                                btnView.Visible = true;
                            }
                            else
                            {
                                MassageSummery("IIS504");
                                //lblError.Text = "No data to display.";
                                btnView.Visible = false;
                            }
                        }
                        else
                        {
                            DataTable dt = new DataTable();
                            int[] dispArr = { 0, 1 };
                            UCGrid1.SetDataSource(dt, dispArr);
                            MassageSummery("IIS504");
                            btnView.Visible = false;
                        }




                    }


                }
                else
                {
                    MassageSummery("IIS518");
                }
            }
            catch (Exception)
            {
                MassageSummery("IIS504");
            }

            


        }



       


       

        protected void drpStatus_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void txtView_Click(object sender, EventArgs e)
        {
            try
            {
                if (Session["cont"] == null)
                {
                    if (Session["firstRow"] != null)
                    {
                        Session["cont"] = ((GridViewRow)Session["firstRow"]);
                        Session.Remove("firstRow");
                    }
                    else
                    {
                        MassageSummery("IIS503");
                    }

                }

                if (Session["cont"] != null)
                {
                    Response.Redirect("~/CustomerServices/PendingProposalDetails.aspx");
                }
                else
                {
                    //lblError.Text = "Please select a pending proposal";
                    MassageSummery("IIS503");
                }
            }
            catch (Exception)
            {

            }
            
            
        }

        #region IDataPage Members

        public void Create()
        {
           
        }

        public void View()
        {
            
        }

        public void Update()
        {
           
        }

        public void Delete()
        {
            
        }

        public void Cancel()
        {
           
        }

        public void GetId(GridViewRow row)
        {
            Session["cont"] = row;
        }

        #endregion

        #region IntTest Members

        public void Next()
        {
            try
            {
                if (UCGrid1.GetText() != "1")
                {
                    pageNo = Convert.ToInt32(UCGrid1.GetText()) + 1;
                    UCGrid1.SetText(pageNo.ToString());

                }
                else
                {
                    pageNo = 2;
                    UCGrid1.SetText("2");

                }


                string csType = string.Empty;
                if (Request.QueryString["cs"] != null)
                {
                    csType = Request.QueryString["cs"].ToString();
                }


                switch (csType)
                {
                    case "ack":
                        SearchAck("ack", pageNo);
                        break;
                    case "pep":
                        SearchAck("pep", pageNo);
                        break;
                    default:
                        break;
                }

            }
            catch (Exception)
            {
            }
            




            

        }

        public void Previous()
        {
            try
            {
                if (UCGrid1.GetText() != "1")
                {
                    pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
                    UCGrid1.SetText(pageNo.ToString());


                    string csType = string.Empty;
                    if (Request.QueryString["cs"] != null)
                    {
                        csType = Request.QueryString["cs"].ToString();
                    }


                    switch (csType)
                    {
                        case "ack":
                            SearchAck("ack", pageNo);
                            break;
                        case "pep":
                            SearchAck("pep", pageNo);
                            break;
                        default:
                            break;
                    }



                }
            }
            catch (Exception)
            {
                
            }

            
        }

        public void Go()
        {
            try
            {
                string csType = string.Empty;
                if (Request.QueryString["cs"] != null)
                {
                    csType = Request.QueryString["cs"].ToString();
                }


                int p = int.Parse(UCGrid1.GetText());
                if (p != 0)
                {
                    try
                    {
                        switch (csType)
                        {
                            case "ack":
                                SearchAck("ack", p);
                                break;
                            case "pep":
                                SearchAck("pep", p);
                                break;
                            default:
                                break;
                        }

                        pageNo = p;
                    }
                    catch (Exception)
                    {

                        throw;
                    }


                }
            }
            catch (Exception)
            {
                
            }
            



           

           
        }

        #endregion
    }
}
